﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Data.SqlClient;
using System.Xml;
using Microsoft.IdentityModel.TokenProcessor;
using OpenIDTokenProcessor;

public partial class main : System.Web.UI.Page
{
	private SqlConnection _cn;
	private DataSet sqlDS;
	private SqlDataAdapter sqlDA;

    protected void Page_Load(object sender, EventArgs e)
    {
		if (Session["sqlConnection"] == null)
			Response.Redirect("StsLogin.aspx");
		else
			_cn = (SqlConnection)Session["sqlConnection"];

		if (_cn.State == ConnectionState.Closed)
			_cn.Open();


		if (Session["sqlDS"] == null || (bool)Session["loaded"] == false)
		{
			Session["sqlDS"] = sqlDS = new DataSet("sts");
			Session["sqlDA"] = sqlDA = new SqlDataAdapter("", _cn);

			updateRPTable();
			updateCMTable();
		}

		if (!Page.IsPostBack)
		{
			Label_UserFullName.Text = "Welcome " + Session["username"].ToString();
		}

		UploadCertificateButton.Click += new EventHandler(UploadCertificateButton_Click);
    }
	protected void UploadCertificateButton_Click(object sender, EventArgs e)
	{
		if (EndPointTextBox.Text == "")
			MessageBox.Show("You have not specified an endpoint.");
		else if (!CertificateUpload.HasFile)
			MessageBox.Show("You have not specified a file.");
		else
		{
			SqlTransaction tran = _cn.BeginTransaction("Transaction");
			try
			{
				byte[] file = CertificateUpload.FileBytes;
				X509Certificate2 cert = new X509Certificate2(file);

				SqlCommand cmd = new SqlCommand("insert into RelyingParties values (@ep, @cn, @cert)", _cn, tran);
				cmd.Parameters.Add("@ep", SqlDbType.VarChar, 100).Value = EndPointTextBox.Text;
				cmd.Parameters.Add("@cn", SqlDbType.VarChar, 100).Value = cert.GetNameInfo(X509NameType.SimpleName,false);
				cmd.Parameters.Add("@cert", SqlDbType.Binary, 1024).Value = file;
				cmd.ExecuteNonQuery();

				cmd.CommandText = "insert into Users_RelyingParties values (@user_id, @ep)";
				cmd.Parameters.Add("@user_id", SqlDbType.Int).Value = Session["user_id"];
				cmd.ExecuteNonQuery();

				tran.Commit();
				updateRPTable();
			}
			catch (Exception ex)
			{
				tran.Rollback();
				MessageBox.Show("ERROR: " + ex.Message);
			}
		}
	}

	void updateRPTable()
	{
		if (sqlDS.Tables["RPTable"] != null)
			sqlDS.Tables["RPTable"].Clear();
		sqlDA.SelectCommand.Parameters.Clear();

		sqlDA.SelectCommand.CommandText = "SELECT Rp.endpoint, Rp.subject FROM RelyingParties Rp "
						+ "INNER JOIN Users_RelyingParties UR ON Rp.endpoint = UR.endpoint "
						+ "INNER JOIN Users U ON UR.user_id = U.user_id "
						+ "WHERE U.user_id = @user_id";
		sqlDA.SelectCommand.Parameters.Add("@user_id", SqlDbType.Int).Value = Session["user_id"];
		sqlDA.Fill(sqlDS, "RPTable");

		RPTable.DataSource = sqlDS.Tables["RPTable"];
		RPTable.DataBind();
		DropDownList1.DataSource = sqlDS.Tables["RPTable"];
		DropDownList1.DataBind();
	}

	void updateCMTable()
	{
		if (sqlDS.Tables["CMTable"] != null)
			sqlDS.Tables["CMTable"].Clear();
		sqlDA.SelectCommand.Parameters.Clear();

		sqlDA.SelectCommand.CommandText = "SELECT * FROM ClaimMapping "
						+ "WHERE endpoint = @endpoint";
		sqlDA.SelectCommand.Parameters.Add("@endpoint", SqlDbType.VarChar, 100).Value = DropDownList1.SelectedValue;
		sqlDA.Fill(sqlDS, "CMTable");

		CMTable.DataSource = sqlDS.Tables["CMTable"];
		CMTable.DataBind();
	}

	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
	{
		if (e.Row.RowType == DataControlRowType.DataRow)
		{
			LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
			l.Attributes.Add("onclick", "javascript:return " +
			"confirm('Are you sure you want to delete this endpoint " +
			DataBinder.Eval(e.Row.DataItem, "endpoint") + "')");
		}
	}
	protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
	{
		if (e.CommandName == "Delete")
		{
			string endpoint = e.CommandArgument.ToString();
			try
			{
				SqlCommand cmd = new SqlCommand("delete from RelyingParties where endpoint=@ep", _cn);
				cmd.Parameters.Add("@ep", SqlDbType.VarChar, 50).Value = endpoint;
				cmd.ExecuteNonQuery();
				updateRPTable();
			}
			catch (Exception Ex)
			{
				MessageBox.Show(Ex.Message);
			}
		}
	}
	protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
	{
	}

	protected void CMTable_RowDataBound(object sender, GridViewRowEventArgs e)
	{
		if (e.Row.RowType == DataControlRowType.DataRow)
		{
			LinkButton l = (LinkButton)e.Row.FindControl("LinkButton2");
			l.Attributes.Add("onclick", "javascript:return " +
			"confirm('Are you sure you want to delete this claim mapping?')");
		}
	}
	protected void CMTable_RowCommand(object sender, GridViewCommandEventArgs e)
	{
		string claimMapping_id = e.CommandArgument.ToString();
		if (e.CommandName == "Delete")
		{
			try
			{
				SqlCommand cmd = new SqlCommand("delete from ClaimMapping where claimMapping_id=@cm", _cn);
				cmd.Parameters.Add("@cm", SqlDbType.Int).Value = claimMapping_id;
				cmd.ExecuteNonQuery();
				updateCMTable();
			}
			catch (Exception Ex)
			{
				MessageBox.Show(Ex.Message);
			}
		}
		else if (e.CommandName == "Change")
		{
			try
			{
				SqlCommand cmd = new SqlCommand("update ClaimMapping set active = ~active where claimMapping_id=@cm", _cn);
				cmd.Parameters.Add("@cm", SqlDbType.Int).Value = claimMapping_id;
				cmd.ExecuteNonQuery();
				updateCMTable();
			}
			catch (Exception Ex)
			{
				MessageBox.Show(Ex.Message);
			}
		}
	}
	protected void CMTable_RowDeleting(object sender, GridViewDeleteEventArgs e)
	{
	}
	protected void ButtonAddClaimMapping_Click(object sender, EventArgs e)
	{
		try
		{
			if (DropDownList1.SelectedIndex == -1)
				MessageBox.Show("Empty endpoint!");
			else
			{
				SqlCommand cmd = new SqlCommand("insert into ClaimMapping (endpoint, fromType, toType, fromValue, toValue) "
					+ "values (@endpoint, @ft, @tt, @fv, @tv)", _cn);
				cmd.Parameters.Add("@endpoint", SqlDbType.VarChar, 100).Value = DropDownList1.SelectedValue;
				cmd.Parameters.Add("@ft", SqlDbType.VarChar, 250).Value = TextBoxFromType.Text;
				cmd.Parameters.Add("@tt", SqlDbType.VarChar, 250).Value = TextBoxToType.Text;
				cmd.Parameters.Add("@fv", SqlDbType.VarChar, 100).Value = TextBoxFromValue.Text;
				cmd.Parameters.Add("@tv", SqlDbType.VarChar, 100).Value = TextBoxToValue.Text;
				cmd.ExecuteNonQuery();

				updateCMTable();
			}
		}
		catch (Exception ex)
		{
			MessageBox.Show("ERROR: " + ex.Message);
		}

	}
	protected void Button2_Click(object sender, EventArgs e)
	{

	}
	protected void ImageButtonGetCard_Click(object sender, ImageClickEventArgs e)
	{
		XmlElement card = ManagedCardWriter.ManagedCardWriter.CreateCard(false);
		if (card == null)
		{
			MessageBox.Show("Error generating informationcard!");
			return;
		}

		Session["exportType"] = "application/crd";
		Session["exportFile"] = "MngdCard.crd";
		Session["exportData"] = card.OuterXml;
		Response.Redirect("~/export.aspx");
	}
	protected void ImageButtonRegisterCard_Click(object sender, ImageClickEventArgs e)
	{
		string xmlToken = XmlTokenField.Value;

		if (string.IsNullOrEmpty(xmlToken))
			return;

		try
		{
			Token token = new Token(xmlToken);
			string ppid = token.Claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier"];

			SqlCommand cmd = new SqlCommand("update Users set samlUniqueId=@samlUniqueId where user_id=@user_id", _cn);

			cmd.Parameters.Add("@user_id", SqlDbType.Int).Value = Session["user_id"];
			cmd.Parameters.Add("@samlUniqueId", SqlDbType.VarChar, 44).Value = token.UniqueID;

			cmd.ExecuteNonQuery();
		}
		catch (Exception ex)
		{
			MessageBox.Show(ex.Message);
		}
	}

	protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
	{
		updateCMTable();
	}
	protected void ImageButtonGetOpenIDCard_Click(object sender, ImageClickEventArgs e)
	{
		XmlElement card = ManagedCardWriter.ManagedCardWriter.CreateCard(true);
		if (card == null)
		{
		    MessageBox.Show("Error generating OpenID Information Card!");
		    return;
		}

		Session["exportType"] = "application/crd";
		Session["exportFile"] = "MngdCard.crd";
		Session["exportData"] = card.OuterXml;
		Response.Redirect("~/export.aspx");
	}
	protected void ImageButtonRegisterOpenIDCard_Click(object sender, ImageClickEventArgs e)
	{
		string xmlToken = XmlTokenField.Value;

		if (string.IsNullOrEmpty(xmlToken))
		    return;

		try
		{
		    OpenIDToken token = new OpenIDToken(xmlToken);
			MessageBox.Show(token.RawOpenIdFields);
		}
		catch (Exception ex)
		{
		    MessageBox.Show(ex.Message);
		}
	}
}
